//创建用户相关小仓库
import { defineStore } from "pinia";
//引入接口
import { reqLogin, reqUserInfo, reqLogout } from "@/api/user";
//用户接口信息数据类型
import type { loginForm, loginResponseData, userInfoResponseData } from "@/api/user/type";
import type { UserState } from './types/type'
//引入操作本地存储的工具方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
//引入常量路由
import { anyRoute, asnycRoute, constantRoute } from "@/router/routers";
import router from "@/router";
//引入深拷贝方法
import {cloneDeep} from 'lodash-es'
//创建用户小仓库
//用于过滤当前用户需要展示的异步路由
function filterAsyncRoute(asnycRoute:any,routes:any){
    return asnycRoute.filter((item:any) => {
        if(routes.includes(item.name)) {
            if(item.children && item.children.length > 0){
                item.children = filterAsyncRoute(item.children,routes)
            }
            return true
        }
    })
}


let useUserStore = defineStore('User', {
    //小仓库存储数据地方
    state: (): UserState => {
        return {
            token: GET_TOKEN(),//用户唯一标识token
            menuRoutes: constantRoute,
            username: '',
            avatar: '',
            buttons:[] //当前用户是否包含某个按钮权限
        }
    },
    //异步|逻辑的地方
    actions: {
        //用户登录的方法 async会返回一个promis对象 三种状态 pending(等待) fulfilled(完成) rejected(拒绝)
        async userLogin(data: loginForm) {
            let result: loginResponseData = await reqLogin(data)
            //登录请求: 成功200->token            
            //登录请求: 失败201->登录失败提示信息
            if (result.code == 200) {
                //pinia仓库存储一些token
                //用于pinia|vuex存储数据其实是利用js对象  并没有持久化
                this.token = (result.data as string)
                //本地存储持久化缓存
                SET_TOKEN((result.data as string))
                //async函数返回结果中的promiseresult为ok
                return 'ok'
            } else {
                return Promise.reject(new Error(result.message))
            }
        },
        //获取用户信息的方法
        async userInfo() {
            // 从接口获取用户信息存储到仓库
            let result: userInfoResponseData = await reqUserInfo()
            if (result.code == 200) {
                this.username = result.data.name
                this.avatar = result.data.avatar
                this.buttons = result.data.buttons
                //计算当前用户需要展示的异步路由
                let userAsyncRoute = filterAsyncRoute(cloneDeep(asnycRoute),result.data.routes);
                //只传入了导航菜单所需数据，未进行路由注册
                this.menuRoutes = [...constantRoute,...userAsyncRoute,anyRoute];
                // 进行路由注册
                [...userAsyncRoute,anyRoute].forEach((route:any) => {
                    router.addRoute(route);
                });
                return 'ok';
            } else {
                return Promise.reject('获取用户信息失败')
            }
        },
        //退出登录方法
        async userLogout() {

            let result: any = await reqLogout()
            if (result.code == 200) {
                this.token = ''
                this.username = ''
                this.avatar = ''
                //删除本地缓存token
                REMOVE_TOKEN()
                return 'ok';
            } else {
                return Promise.reject(new Error(result.message))
            }
        }

    },
    getters: {

    }

})

export default useUserStore